<template>
  <van-nav-bar
    title="订单结算"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
  />
  <van-cell title="收货人" icon="location-o" />
  <van-contact-card
    type="edit"
    :tel="contactInfo.tel"
    :name="contactInfo.name"
    @click="onSelect"
  />
  <van-cell title="您购买的商品" icon="shopping-cart-o" />

  <div class="products">
    <div class="imgwarp" v-for="item in cartProducts">
      <img :src="item.productImg" />
    </div>
    <div class="imgwarp qty">
      <p>共 {{ cartProducts.length }} 件</p>
    </div>
  </div>
  <van-cell title="商品总金额" icon="refund-o" :value="'¥' + totalAmount" />
  <van-cell title="京豆抵扣" icon="shield-o">
    <template #value>
      <van-stepper v-model="jd" min="0" max="100" />
    </template>
  </van-cell>
  <van-cell title="应付金额" icon="refund-o" :value="'¥' + needPayAmount" />

  <van-submit-bar
    :price="needPayAmount * 100"
    button-text="提交订单"
    @submit="onSubmit"
  />

  <van-action-sheet
    v-model:show="show"
    :actions="actions"
    cancel-text="取消"
    description="请选择收货人"
    close-on-click-action
    @select="actionSelect"
  />
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import { showToast } from "vant";
import { cartApi, productApi, addressApi, orderApi } from "@/api/index";
import { useRoute, useRouter } from "vue-router";
import { appStore } from "@/store/appStore";
import { storeToRefs } from "pinia";

let { userId, phone } = storeToRefs(appStore());
const route = useRoute(); //不带r的是获取当前页面url相关参数
const router = useRouter(); //代r的是负责页面跳转

//联系人信息
const contactInfo = reactive({
  tel: "",
  name: "",
  addressId: 0,
});

const jd = ref(0);
const totalAmount = ref(0);
const needPayAmount = ref(0);
const cartProducts = ref([]);
const show = ref(false);
const actions = ref([]);

const newCartIds = ref();

onMounted(() => {
  let cartIds = route.query.cartIds;
  if (Array.isArray(cartIds)) {
    newCartIds.value = cartIds;
  } else {
    newCartIds.value = [cartIds];
  }

  callCartApi();

  callAddressApi();
});

//查询收货地址
const callAddressApi = () => {
  addressApi.getList.call({ userId: userId.value }).then((res: any) => {
    res.forEach((item: any) => {
      item.tel = item.phone;
      item.subname =
        item.province + item.city + item.country + item.addressDetail;
      if (item.isDefault === 0) {
        item.isDefault = true;
      } else {
        item.isDefault = false;
      }
    });
    actions.value = res;

    const defaultAddress = actions.value.filter((p) => p.isDefault === true)[0];
    if (defaultAddress != undefined) {
      contactInfo.addressId = defaultAddress.id;
      contactInfo.name = defaultAddress.name;
      contactInfo.tel = defaultAddress.tel;
    }
  });
};

//查询结算的购物车商品
const callCartApi = () => {
  cartApi.select
    .call({ userId: userId.value, ids: newCartIds.value })
    .then((res: any) => {
      cartProducts.value = res;
      res.forEach((item: any) => {
        totalAmount.value = Number(
          Number(item.productPrice * item.productQty).toFixed(2)
        );
      });
      console.log(totalAmount);
      needPayAmount.value = totalAmount.value;
    });
};

//监视京豆的变化
watch(
  () => jd.value,
  (newValue, oldValue) => {
    needPayAmount.value = Number(
      Number(totalAmount.value - jd.value * 0.01).toFixed(2)
    );
  }
);

//选择收货地址菜单
const onSelect = () => {
  show.value = true;
};

//选中
const actionSelect = (action: any, index: number) => {
  contactInfo.addressId = action.id;
  contactInfo.name = action.name;
  contactInfo.tel = action.tel;
};
//提交
const onSubmit = () => {
  const products: any = [];
  cartProducts.value.forEach((item: any) => {
    products.push({
      productId: item.productId,
      productName: item.productName,
      productImg: item.productImg,
      price: item.productPrice,
      qty: item.productQty
    });
  });
  //构建参数
  const params = {
    userId: userId.value,
    addressId: contactInfo.addressId,
    totalPrice: needPayAmount.value,
    jd: jd.value,
    status: 0,
    orderItems: products
  };
  console.log(params)
  orderApi.add.call(params).then((res: any) => {
    console.log(res);
    if (res.needPayAmount === 0) {
      router.push({ name: "order-list" });
    } else {
      router.push({
        name: "order-pay",
        query: { id: res.orderId, needPayAmount: res.needPayAmount },
      });
    }
  });
};
const onClickLeft = () => history.back();
</script>
<style scoped>
.products {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 96%;
  flex-flow: wrap;
  margin-left: 20px;
  margin-right: 20px;
}

.imgwarp {
  width: 4rem;
  height: 4rem;
  margin-right: 0.4rem;
  margin-top: 0.2rem;
}

.imgwarp img {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.qty {
  background-color: #ccc;
}

.qty p {
  text-align: center;
  height: 2rem;
  line-height: 2rem;
  color: tomato;
  font-size: 12px;
}
</style>